import time
from datetime import datetime
import struct
import serial

# 构建数据包
frame_header = 0x0606  # 2字节
total_length = 28  # 1字节
command_type = 0x01020304  # 4字节
control_param = 0x0102030405060708  # 8字节

frame_tail = 0x66AA  # 2字节
package_num=1

def get_time(p=False):
    # 获取当前 UTC 时间
    current_utc_time = datetime.utcnow()
    # 获取年、月、日、时、分、秒和毫秒
    year = current_utc_time.year
    year = int(str(year)[-2::])
    month = current_utc_time.month
    day = current_utc_time.day
    hour = current_utc_time.hour
    minute = current_utc_time.minute
    second = current_utc_time.second
    millisecond = round(current_utc_time.microsecond / 1000)

    if p == True:
        formatted_time_with_ms = f"{year}-{month}-{day} T {hour}:{minute}:{second}.{millisecond} UTC"
        print("Current UTC time with milliseconds:", formatted_time_with_ms)
    # time_stamp=struct.pack('!BBBBBBH',year,month,day,hour,minute,second,millisecond)

    return (year, month, day, hour, minute, second, millisecond)


def calculate_checksum(data):
    return sum(data) & 0xFF


def Assembly_command(intervals):
    global package_num
    year, month, day, hour, minute, second, millisecond = get_time(p=False)

    # H:unsigned short 2
    # Q:unsigned long long 8
    # I:unsigned int 4
    # B:unsigned char 1
    if package_num<int('FFFF',16):
        reserved = struct.pack('!H', package_num)  # 2字节
    else:
        package_num=0
    cmd = struct.pack('!B BBBBBBH I Q', total_length, year, month, day, hour, minute, second, millisecond, command_type,
                      control_param) + reserved
    checksum = calculate_checksum(cmd)  # 1字节

    total_cmd = struct.pack('!H', frame_header) + cmd + struct.pack('!BH', checksum, frame_tail)

    return total_cmd
    # print(total_cmd)


time_intervals = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
ser = serial.Serial('/dev/ttyUSB0', 115200)
# cmd = Assembly_command(0.3)
# # Assembly_command(0.3)
# time.sleep(0.3)
# ser.write(cmd)
bytes_len=0
while 1:

    try:
        # for i in time_intervals:
        i=0.3
        cmd = Assembly_command(i)
        # Assembly_command(0.3)
        time.sleep(i)
        ser.write(cmd)
        bytes_len +=28
        package_num+=1

    except:
        ser.close()
